package com.xyf.basicrtc

import android.os.Environment
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import java.io.FileOutputStream
import java.io.IOException
import java.net.URI

class PushHelp(surfaceView: SurfaceView, private val width: Int, private val height: Int,clientRole:Int) : SurfaceHolder.Callback {
    private var decodeH265: DecodeH264? = null
    private var socketServer: SocketServer? = null
    private var socketClient: SocketClient? = null

    private var onH265Frame = ::sendH265
    private var mOnRemoteFrame = ::onRemoteFrame

    private var encodeH265: EncodeH264 = EncodeH264(width, height).apply {
        onFrame = onH265Frame
        start()
    }


    init {
        surfaceView.holder.addCallback(this)
        if (clientRole == 1){
            socketServer = SocketServer(PORT).apply {
                this.onRemoteFrame = mOnRemoteFrame
            }
        }else{
            socketClient = SocketClient(URI("ws://192.168.31.18:10086")).apply {
                onRemoteFrame = mOnRemoteFrame
            }
        }

        socketServer?.start()
        socketClient?.connect()

    }

    private fun sendH265(h264Frame:ByteArray){
//        writeBytes(h264Frame)
        socketServer?.sendData(h264Frame)
        socketClient?.sendData(h264Frame)
    }


    fun writeBytes(array: ByteArray?) {
        var writer: FileOutputStream? = null
        try {
            // 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
            writer = FileOutputStream(
                Environment.getExternalStorageDirectory().toString() + "/codec.h264", true
            )
            writer.write(array)
            writer.write('\n'.code)
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            try {
                writer?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }




    fun encodeFrame(data: ByteArray){
        encodeH265.encodeFrame(data)
    }
    private fun onRemoteFrame(data: ByteArray){
        Log.i("onRemoteFrame","data = ${data.size} decodeH265 = $decodeH265")
        decodeH265?.decode(data)
//        writeBytes(data)
    }


    companion object{
        const val PORT = 10086
    }


    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {

    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {

    }
    override fun surfaceCreated(holder: SurfaceHolder) {
        decodeH265 = DecodeH264(holder.surface, width, height)
    }

}
